const express = require('express');
const bodyParser = require('body-parser');
const app = express();

const cors = require('cors');
app.use(cors({
    origin: '*',
    credentials: true
}));




const path = require('path');
app.use(express.static(path.join(__dirname, 'public')));

// body-parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


// 密钥 -- token
const config = require('./config')
// 解析 token 的中间件
const expressJWT = require('express-jwt')
// 使用 .unless({ path: [/^\/api\//] }) 指定哪些接口不需要进行 Token 的身份认证
app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: ['/api/login', 
    '/api/register', '/api/addCar', '/api/delCarItem', 
    '/api/updateItemNum', '/api/submitOrder', '/api/orderList', '/api/goods',
    /^\/admin\//] }))

// routes

//! 用户--前台接口
const getGoodsList = require('./router/goods/goodsList')
app.use('/api', getGoodsList);

const userAccountHandler = require('./router/user/account')
app.use('/api', userAccountHandler);

const carHandler = require('./router/goods/car')
app.use('/api', carHandler)

const subOrder = require('./router/user/order')
app.use('/api', subOrder)





//! 管理员--后台接口
const adminLogin = require('./router/admin/login')
app.use('/admin', adminLogin)

const getUserList = require('./router/admin//userList')
app.use('/admin', getUserList)


const goodsList = require('./router/admin/goods')
app.use('/admin', goodsList)


const getOrderList = require('./router/admin/order')
app.use('/admin', getOrderList)



app.use((err, req, res, next) =>{
    console.log(err);
    
    if (err.name === 'UnauthorizedError') {
        res.send({
            status: 408,
            message: 'Token 失效'
        })
    }
})


app.listen(3000, () =>{
    console.log('Server is running on port 3000');
})